package com.example.thegreatwall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.thegreatwall.common.R;
import com.example.thegreatwall.entity.Product;
import com.example.thegreatwall.entity.ProductDetail;
import com.example.thegreatwall.entity.TProduct;
import com.example.thegreatwall.mapper.InventoryMapper;
import com.example.thegreatwall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.thegreatwall.mapper.OrderMapper;
import com.example.thegreatwall.entity.Order;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private ProductService productService;

    @Autowired
    private TProductService tProductService;

    /**
     * 下订单
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insOrder(Order order) {
        ProductDetail one = productDetailService.getOne(new QueryWrapper<ProductDetail>().eq("product_detail_id",order.getDetailId()));
        int lockSuccess = inventoryService.reqUpdinventory(
                one.getProductId(),
                one.getProductType(),
                order.getTourdate().substring(0,10),
                order.getQuantity()
        );
        if (lockSuccess==0) {
            throw new RuntimeException("库存不足");
        }
        Product productId  = null;
        TProduct tProductId=null;
    if(one.getProductType()==0) {
       productId = productService.getOne(new QueryWrapper<Product>().eq("product_id", one.getProductId()));

    }else {
        tProductId = tProductService.getOne(new QueryWrapper<TProduct>().eq("t_product_id", one.getProductId()));
    }
    //当商品下架了之后就不生成订单
        if (one.getStatus() == 0 || (productId != null && productId.getStatus() == 0) || (tProductId != null && tProductId.getStatus() == 0)) {
            throw new RuntimeException("套餐已被下架");
        }

        //新增订单
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        order.setOrderNo("E"+now.format(formatter));
        save(order);
        String orderNo = "E" + now.format(formatter);
        return new R().setMsg("新增成功").addDate("orderno",orderNo);
    }


    @Scheduled(fixedRate = 60_000) // 60秒执行一次
    @Transactional(rollbackFor = Exception.class)
    public void checkAndReleaseTimeoutOrders() {
        System.out.println("hi,你到底也是检查没检查啊");
        // 1. 查询15分钟前创建的未支付订单
        LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(15);
        List<Order> timeoutOrders = baseMapper.selectList(
                new QueryWrapper<Order>()
                        .eq("status", 0) // 假设0=未支付
                        .lt("create_time", timeoutTime)
        );

        // 2. 逐个释放库存
        timeoutOrders.forEach(order -> {
            try {
                // 2.1 查询关联的商品信息
                ProductDetail detail = productDetailService.getOne(
                        new QueryWrapper<ProductDetail>()
                                .eq("product_detail_id", order.getDetailId())
                );

                // 2.2 释放库存
                boolean released = inventoryService.releaseLockedInventory(
                        detail.getProductId(),
                        detail.getProductType(),
                        order.getTourdate(),
                        order.getQuantity()
                );

                // 2.3 更新订单状态为"已取消"
                if (released) {
                    order.setStatus(2); // 假设2=已取消
                    updateById(order);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

}
